package edu.wtbu.cs.bishe.service.impl;

import edu.wtbu.cs.bishe.service.EmailService;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class EmailServiceImpl implements EmailService {

    private final JavaMailSender mailSender;

    @Value("${spring.mail.properties.mail.smtp.from}")
    String emailFrom;

    public void sendVerificationCode(String email, String code) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(emailFrom);
            helper.setTo(email);
            helper.setSubject("您的注册验证码");
            String content = """
                <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
                    <h2 style="color: #2c3e50;">欢迎注册我们的服务</h2>
                    <p>您的验证码是：<strong>%s</strong></p>
                    <p style="color: #7f8c8d;">该验证码将在10分钟后失效</p>
                </div>
                """.formatted(code);
            helper.setText(content, true);
        } catch (MessagingException e) {
            throw new RuntimeException("邮件发送失败", e);
        }
        mailSender.send(message);
    }
}


